package tech.aistar.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import tech.aistar.entity.Cart;
import tech.aistar.entity.User;
import tech.aistar.service.ICartService;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Created by Administrator on 2020/1/1 0001.
 */
@Controller
public class CartController {
    @Autowired
    private ICartService cartService;

    @GetMapping("/addCart")
    public String addCart(Cart cart){

        cartService.save(cart);
        return "redirect:/cart/find";
    }
    @GetMapping("/del1")
    public String del1(Integer id){

        cartService.deleteById(id);

        return "redirect:/cart/find";
    }
    @GetMapping("/delMore1")
    public String delmore1(String ids){

        //根据:进行切割
        String[] arr = ids.split(":");

        for(String sid:arr){
            cartService.deleteById(Integer.valueOf(sid));
        }

        return "redirect:/cart/find";
    }
    /**
     * 查询当前登陆的用户的购物车
     * @return
     */
    @GetMapping("/cart/find")
    public String find(HttpSession session,Model model){
        //获取当前登陆的用户在作用域中的数据 - ${userLogin}
        User user = (User) session.getAttribute("userLogin");

        //根据用户名来查询这个用户的cart
        List<Cart> carts = cartService.findByUserName(user.getUsername());

        //将这个购物车集合放入到request作用域
        model.addAttribute("carts",carts);
        return "cart/cart";
    }
}